﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Globalization;
using System.Threading;
using DevExpress.XtraSplashScreen;
using DevExpress.XtraBars.Helpers;
using DevExpress.XtraBars;
using HouseSecretary.Common;
using DevExpress.Utils;
using DevExpress.XtraEditors.Controls;
using HouseSecretary.Base;
using System.Reflection;
using System.IO;
using System.Xml;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;
using Newtonsoft.Json;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
using System.Collections;

namespace HouseSecretary
{
    public partial class MainForm : Base.BaseForm
    {
        /// <summary>
        /// 是否显示主页面
        /// </summary>
        private bool IsShowManiForm = false;


        //string jsonMsg = "";
        //string code = "";
        //string msg = "";
        //public static ManualResetEvent mre;
        //public static ManualResetEvent mre2;


        public MainForm()
            : base(false)
        {
            InitializeComponent();
        }

        /// <summary>
        /// 主窗口载入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {

            XtraMessageBoxForm.ForceShortBox = true;//设置程序的提示框 自动换行

            CultureInfo culinfo = new CultureInfo("zh-CN");
            System.Globalization.DateTimeFormatInfo dinfo = (DateTimeFormatInfo)Thread.CurrentThread.CurrentCulture.DateTimeFormat.Clone(); //这个是只读的,所以先复制一份
            dinfo.ShortDatePattern = "yyyy-MM-dd";
            dinfo.LongDatePattern = "yyyy-MM-dd";
            dinfo.ShortTimePattern = "HH:mm";
            dinfo.LongTimePattern = "HH:mm:ss";
            culinfo.DateTimeFormat = dinfo;
            Thread.CurrentThread.CurrentCulture = culinfo; //只更改当前进程的日期格式

            Base.GlobalParams.GLOBAL_VERSION = base.AssemblyVersion;//版本
            SplashScreenManager.ShowForm(this, typeof(SplashScreenInitForm), false, false, false);//进度条
            SplashScreenManager.Default.SendCommand(SplashScreenInitForm.SplashScreenCommand.SetMessage, "正在装载系统,请耐心等待...");

            //默认皮肤
            string skinStyleName = Common.ConfigHelper.GetConfigString("SkinStyleName");
            if (skinStyleName != "")
            {
                DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(skinStyleName);
            }
            SplashScreenManager.CloseForm(false);

            
            
        }

        /// <summary>
        /// 第一次窗体显示时的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Shown(object sender, EventArgs e)
        {
            InitPage();

            LoginForm frmLogin = new LoginForm();
            DialogResult dr = frmLogin.ShowDialog();
            
        }

        private void InitPage()
        {
            InitRibbon();
            //打开房源采集窗口
            BarButtonItem barCollect = GetRibbonBarItemByName("houseSrcInfoWebDC") as BarButtonItem;
            barCollect.PerformClick();
        }

        #region 打开窗口相关

        private Dictionary<string, string> dicFrmMenuName = new Dictionary<string, string>();
        /// <summary>
        /// 当前点击菜单名
        /// </summary>
        private string CurrentMnuName = "";
        /// <summary>
        /// 打开子窗体
        /// <creator>zhongyl</creator>
        /// <date>2011-12-17</date>
        /// </summary>
        /// <param name="ChildTypeString"></param>
        private void OpenWindow(string childTypeString, string mnuName, bool isChildClose = false, Model.CommonDlgParameters CommDlgParaModel = null)
        {
            base.OpenWaitForm(this.Handle);
            CurrentMnuName = mnuName;
            Form myChild = null;
            try
            {
                object[] objParams = null;
                if (CommDlgParaModel != null)
                {
                    objParams = new object[] { CommDlgParaModel };
                }

                if (isChildClose)
                {
                    foreach (Form f in this.MdiChildren)
                    {
                        if (f.GetType().ToString() == childTypeString)
                        {
                            f.Close();
                            break;
                        }
                    }
                }

                if (!ContainMDIChild(childTypeString))
                {
                    Assembly assembly = Assembly.GetExecutingAssembly();
                    Type typForm = assembly.GetType(childTypeString);
                    Object obj = typForm.InvokeMember(
                        null,
                        BindingFlags.DeclaredOnly |
                        BindingFlags.Public | BindingFlags.NonPublic |
                        BindingFlags.Instance | BindingFlags.CreateInstance,
                        null,
                        null,
                        objParams
                        );
                    if (obj != null)
                    {
                        myChild = obj as Form;

                        if (!dicFrmMenuName.ContainsKey(myChild.Name))
                        {
                            dicFrmMenuName.Add(myChild.Name, mnuName);
                        }
                        myChild.MdiParent = this;
                        MdiClient client = myChild.Parent as MdiClient;
                        myChild.Size = client.ClientSize;

                        myChild.Show();
                        myChild.Focus();
                        myChild.Location = new Point(0, 0);
                    }
                }
            }
            finally
            {
                base.CloseWaitForm();
            }
        }

        /// <summary>
        /// 查找子窗体
        /// <creator>zhongyl</creator>
        /// <date>2011-12-17</date>
        /// </summary>
        /// <param name="ChildTypeString"></param>
        /// <returns></returns>
        private bool ContainMDIChild(string childTypeString)
        {
            Form myMDIChild = null;
            foreach (Form f in this.MdiChildren)
            {
                if (f.GetType().ToString() == childTypeString)
                {
                    myMDIChild = f;
                    break;
                }
            }
            if (myMDIChild != null)
            {
                myMDIChild.TopMost = true;
                myMDIChild.Show();
                myMDIChild.Focus();
                return true;
            }
            else
                return false;
        }


        /// <summary>
        /// <creator>zhongyl</creator>
        /// <date>2011-12-17</date>
        /// </summary>
        /// <param name="childTypeString"></param>
        private void OpenDialogWindow(string childTypeString, string mnuName, Model.CommonDlgParameters CommonDlgParametersModel = null)
        {
            base.OpenWaitForm(this.Handle);
            object[] objParams = null;
            if (CommonDlgParametersModel != null)
            {
                objParams = new object[] { CommonDlgParametersModel };
            }
            Form myChild = null;
            try
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                Type typForm = assembly.GetType(childTypeString);
                Object obj = typForm.InvokeMember(
                       null,
                       BindingFlags.DeclaredOnly |
                       BindingFlags.Public | BindingFlags.NonPublic |
                       BindingFlags.Instance | BindingFlags.CreateInstance,
                       null,
                       null,
                       objParams);
                if (obj != null)
                {
                    myChild = obj as Form;
                    CurrentMnuName = mnuName;
                    Image image = base.GetMenuImageCollection().Images[CurrentMnuName];
                    if (image != null)
                    {
                        Bitmap bt = (Bitmap)image;
                        myChild.Icon = Icon.FromHandle(bt.GetHicon());
                    }
                    else
                    {
                        myChild.Icon = this.Icon;
                    }
                    myChild.Owner = this;
                    myChild.ShowDialog();
                }
            }
            finally
            {
                base.CloseWaitForm();

            }
        }


        #endregion

        

        #region Ribbon相关

        /// <summary>
        /// 根据item名获取item
        /// </summary>
        /// <param name="buttonName"></param>
        /// <returns></returns>
        private BarItem GetRibbonBarItemByName(string buttonName)
        {
            BarItem bi = null;
            for (int i = 0; i < ribbonTool.Items.Count; i++)
            {
                if (ribbonTool.Items[i].Name == buttonName)
                {
                    bi = ribbonTool.Items[i];
                    break;
                }

            }
            return bi;
        }

        private void InitRibbon()
        {
            #region 操作

            #region 操作

            BarButtonItem barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "房源采集";
            barButtonItem.Name = "houseSrcInfoWebDC";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_houseSrcInfoWebDC", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonHouseSrcInfoWebDC);
            rbnGrpEdit.ItemLinks.Add(barButtonItem);
/*
            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "房源群发";
            barButtonItem.Name = "houseSrcBulkPub";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_houseSrcBulkPub", imgLargeCollectToolBar);
            rbnGrpEdit.ItemLinks.Add(barButtonItem);
*/
            #endregion

            #region 退出

            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "退出";
            barButtonItem.Name = "exit";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_exit", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonExit);

            rbnGrpLogout.ItemLinks.Add(barButtonItem);
            #endregion

            #endregion

            #region 设置
            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "经纪人中心";
            barButtonItem.Name = "realtorCenter";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_realtorCenter", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonRealtorCenter);
            rbnGrpUpset.ItemLinks.Add(barButtonItem);
/*
            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "群发端口设置";
            barButtonItem.Name = "houseSrcPubInterface";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_houseSrcPubInterface", imgLargeCollectToolBar);
            rbnGrpUpset.ItemLinks.Add(barButtonItem);

            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "易灵（立得）账户设置";
            barButtonItem.Name = "elingrealSetup";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_elingrealSetup", imgLargeCollectToolBar);
            rbnGrpUpset.ItemLinks.Add(barButtonItem);
*/
            #endregion


        }

        /// <summary>
        /// 房源采集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonHouseSrcInfoWebDC(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            OpenWindow(typeof(HouseForm.HouseSrcInfoWebDCForm).ToString(), e.Item.Name);
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonExit(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (DialogResult.Yes == XtraMessageBox.Show("您确认要退出【房秘书】系统吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk,MessageBoxDefaultButton.Button2))
            {
                Application.Exit();
                this.Close();
            }
        }


        /// <summary>
        /// 经纪人中心
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonRealtorCenter(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            OpenWindow(typeof(HouseForm.RealtorCenterForm).ToString(), e.Item.Name);
        }

        #endregion



        #region 工具栏相关


        /// <summary>
        /// [已过时]设置按钮的Enabled属性
        /// <creator>wangl</creator>
        /// <date>2011-12-23</date>
        /// </summary>
        /// <param name="buttonName">按钮的text值</param>
        /// <param name="enabled">是否可用</param>
        ///[Obsolete("已过时,请选用SetButtonEnabledByName方法")]
        private void SetButtonsEnabled(string buttonCaption, bool enabled)
        {
            for (int i = 0; i < barMainManager.Items.Count; i++)
            {
                if (barMainManager.Items[i].Caption == buttonCaption)
                {
                    barMainManager.Items[i].Enabled = enabled;
                    break;
                }

            }
        }

        /// <summary>
        /// 获取工具栏项
        /// </summary>
        /// <param name="buttonCaption"></param>
        /// <returns></returns>
        private BarItem GetBarItem(string buttonCaption)
        {
            BarItem bi = null;
            for (int i = 0; i < barMainManager.Items.Count; i++)
            {
                if (barMainManager.Items[i].Caption == buttonCaption)
                {
                    bi = barMainManager.Items[i];
                    break;
                }

            }
            return bi;
        }
        /// <summary>
        /// 根据名字获取工具栏项
        /// </summary>
        /// <param name="buttonName"></param>
        /// <returns></returns>
        private BarItem GetBarItemByName(string buttonName)
        {
            BarItem bi = null;
            for (int i = 0; i < barMainManager.Items.Count; i++)
            {
                if (barMainManager.Items[i].Name == buttonName)
                {
                    bi = barMainManager.Items[i];
                    break;
                }

            }
            return bi;
        }
        /// <summary>
        /// 设置按钮的Enabled属性 (根据名字)
        /// <creator>wangl</creator>
        /// <date>2012-04-16</date>
        /// </summary>
        /// <param name="buttonName"></param>
        /// <param name="enabled"></param>
        private void SetButtonEnabledByName(string buttonName, bool enabled)
        {
            for (int i = 0; i < barMainManager.Items.Count; i++)
            {
                if (barMainManager.Items[i].Name == buttonName)
                {
                    barMainManager.Items[i].Enabled = enabled;
                    break;
                }

            }
        }
        /// <summary>
        /// 设置按钮的文本
        /// <creator>wangl</creator>
        /// <date>2012-04-16</date>
        /// </summary>
        /// <param name="buttonName"></param>
        /// <param name="buttonCaption"></param>
        private void SetButtnCaption(string buttonName, string buttonCaption)
        {
            for (int i = 0; i < barMainManager.Items.Count; i++)
            {
                if (barMainManager.Items[i].Name == buttonName)
                {
                    barMainManager.Items[i].Caption = buttonCaption;
                    break;
                }

            }
        }
        /// <summary>
        /// 设置按钮imageList中的imageIndex
        /// <creator>wangl</creator>
        /// <date>2012-04-16</date> 
        /// </summary>
        /// <param name="imgName"></param>
        /// <returns></returns>
        private void SetButtonImageIndex(string buttonName, string imgName, ImageCollection imgCollect)
        {
            for (int i = 0; i < barMainManager.Items.Count; i++)
            {
                if (barMainManager.Items[i].Name == buttonName)
                {
                    Image img = imgCollect.Images[imgName];
                    for (int j = 0; j < imgCollect.Images.Count; j++)
                    {
                        if (imgCollect.Images[j] == img)
                        {
                            barMainManager.Items[i].ImageIndex = j;
                            break;
                        }

                    }
                    break;
                }

            }

        }
        #endregion

        #region 皮肤相关代码

        /// <summary>
        /// 递归绑定皮肤菜单事件
        /// <user>wangl</user>
        /// <date>2013-02-17</date> 
        /// </summary>
        private void BingSkinItemEvent(LinkPersistInfo liParent)
        {
            foreach (LinkPersistInfo liChild in ((BarSubItem)liParent.Item).LinksPersistInfo)
            {
                if (liChild.Item is BarSubItem)
                {
                    BingSkinItemEvent(liChild);
                }
                else
                {
                    liChild.Item.ItemClick += new ItemClickEventHandler(Item_MenuItemClick);
                    if (liParent.Item.Caption == DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName)
                    {
                        ((BarButtonItem)liParent.Item).ButtonStyle = BarButtonStyle.Check;
                    }
                }
            }
        }

        /// <summary>
        /// 点击皮肤样式菜单事件
        /// <user>wangl</user>
        /// <date>2012-03-03</date>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Item_MenuItemClick(object sender, ItemClickEventArgs e)
        {
            //将皮肤名称写入到config文件中
            Common.ConfigHelper.SeTconfigKeyValue("SkinStyleName", e.Item.Caption);

        }
        #endregion


        #region 主窗体事件


        /// <summary>
        /// 关闭改为隐藏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (IsShowManiForm)
            {
                if (e.CloseReason == CloseReason.UserClosing)//当用户点击窗体右上角X按钮或(Alt + F4)时 发生           
                {
                    e.Cancel = true;
                    this.ShowInTaskbar = false;
                    this.Hide();
                }
            }
            else
            {
                e.Cancel = false;
            }
        }

      
        #endregion

        

        


    }
}